# -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2016  德清武康开源软件().
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from odoo import api, fields, models, tools, _
from odoo.exceptions import UserError

class PosOrder(models.Model):
    _inherit = "pos.order"

    def add_payment(self, data):
        """Create a new payment for the order"""
        self.ensure_one()
        args = self._prepare_bank_statement_line_payment_values(data)
        context = dict(self.env.context)
        context.pop('pos_session_id', False)
        order_id = self.env['house.order'].search(
            [('partner_id', '=', args.get("partner_id")), ('state', '=', 'chick_in')], limit=1)
        if args.get("journal_id"):
            journal = self.env['account.journal'].search([('id', '=', args.get("journal_id"))])
        pos_id = self.env['pos.order'].search([('id', '=', args.get("pos_statement_id"))])
        print(args)
        if journal.is_house_pay:
            if not order_id:
                raise UserError("没有找到已入住的客户!")
                #todo 样式有点丑,要改进一下
            for i in pos_id.lines:
                self.env['have.meals.line'].create({
                    'name': i.product_id.id,
                    'order_id': order_id.id,
                    'date': args.get("date"),
                    'amount': i.price_subtotal_incl,
                    'is_channel_pay': False,
                })
        self.env['account.bank.statement.line'].with_context(context).create(args)
        self.amount_paid = sum(payment.amount for payment in self.statement_ids)
        return args.get('statement_id', False)

class AccountJournal(models.Model):
    _inherit = "account.journal"

    is_house_pay = fields.Boolean(default=False, string="同步到民舍订单付款")